#include <iostream>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "datatype.h"
#include "client.h"


client::client(const char *ip,const char *port)
{
	if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) < 0)
	{
		errlog("socket");
	}

	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = inet_addr(ip);
	serveraddr.sin_port = htons(atoi(port));
	
	clientaddr.sin_family = AF_INET;
}
client::~client()
{

}
int client::setUser(const char *_name,const char *_password)
{
	strcpy(s_message.name,_name);
	strcpy(s_message.text,_password);
}
int client::my_send(struct sockaddr_in &targetAddr)
{
	//d_printf("send to:%s %d\n",inet_ntoa(targetAddr.sin_addr),ntohs(targetAddr.sin_port));
	if(sendto(sockfd,&s_message,sizeof(s_message),0, \
		(struct sockaddr *)&targetAddr,sizeof(targetAddr)) < 0)
	{
		errlog("sendto");
	}
}
int client::my_receive(struct sockaddr_in &targetAddr)
{
	socklen_t len = sizeof(targetAddr);
	if(recvfrom(sockfd,&r_message,sizeof(r_message),0, \
		(struct sockaddr *)&targetAddr,&len) < 0)
	{
		errlog("recvfrom");
	}
	//d_printf("receive from:%s %d\n",inet_ntoa(targetAddr.sin_addr),ntohs(targetAddr.sin_port));
}
int client::start(void)
{
	pid_t pid;
	if((pid = fork()) < 0)
	{
		errlog("fork");	
	}

	if(pid == 0)
	{
		child_process();
	}
	else
	{
		parent_process();
	}
}
int client::child_process(void)
{
	while(1)
	{
		my_receive(serveraddr);
		s_message.type = MSG_TYPE_LOGOUT;
		cout << "receive from " << r_message.name << ": " << r_message.text << endl;
	}
}
int client::parent_process(void)
{
	//先发送输入好的账号和密码以登录
	my_send(serveraddr);
	while(1)
	{	
		s_message.type = MSG_TYPE_MESSAGE;
		cin.getline(s_message.text,MESSAGE_NAME_SIZE);

		if(strncmp(s_message.text,"quit",5) == 0)
		{
			s_message.type = MSG_TYPE_LOGOUT;
		}

		my_send(serveraddr);
		if(strncmp(s_message.text,"quit",5) == 0)
		{
			exit(0);
		}
	}
}
